package cn.workreport.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;

@Slf4j
@SpringBootTest
public class CodeGenerator {
    /**
     * 数据源配置（使用 spring 配置的数据源）
     */
    @Value("${spring.datasource.url}")
    private String datasourceUrl;

    @Value("${spring.datasource.username}")
    private String datasourceUsername;

    @Value("${spring.datasource.password}")
    private String datasourcePassword;

    /**
     * 设置作者
     */
    private static final String AUTHOR = "yyf";

    /**
     * 设置父包模块名
     */
    private static final String MODULE_NAME = "report";

    /**
     * 设置需要生成的表名
     */
    private static final String TABLE_NAME = "t_report_record";

    /**
     * 设置过滤表前缀
     */
    private static final String TABLE_PREFIX = "t_";

    /**
     * 执行生成代码包
     * @throws IOException
     */
    @Test
    public void generate () throws IOException {
        log.info("datasourceUrl =>" + datasourceUrl);
        log.info("datasourceUsername =>" + datasourceUsername);
        log.info("datasourcePassword =>" + datasourcePassword);

        File file = new File("");
        String outputDirPath = file.getCanonicalPath() + File.separator
                + "src" + File.separator
                + "main" + File.separator
                + "java" + File.separator;
        log.info("指定输出目录路径: " + outputDirPath);

        String xmlFileOutputPath = file.getCanonicalPath() + File.separator
                + "src" + File.separator
                + "main" + File.separator
                + "resources" + File.separator
                + "mappers" ;
        log.info("指定mapperXml生成路径: " + xmlFileOutputPath);

        FastAutoGenerator.create(datasourceUrl, datasourceUsername, datasourcePassword)
            .globalConfig(builder -> {
                builder.author(AUTHOR) // 设置作者
                        .enableSwagger() // 开启 swagger 模式
                        .fileOverride() // 覆盖已生成文件
                        .outputDir(outputDirPath); // 指定输出目录
            })
            .packageConfig(builder -> {
                builder.parent("cn.workreport.modules") // 设置父包名
                        .moduleName(MODULE_NAME) // 设置父包模块名
                        .pathInfo(Collections.singletonMap(OutputFile.mapperXml, xmlFileOutputPath)); // 设置mapperXml生成路径
            })
            .strategyConfig(builder -> {
                builder.addInclude(TABLE_NAME) // 设置需要生成的表名
                        .addTablePrefix(TABLE_PREFIX); // 设置过滤表前缀
            })
            .templateEngine(new VelocityTemplateEngine()) // 使用Velocity引擎模板
            .execute();
    }

    /**
     * 执行初始化数据库脚本
     */
    @Test
    public void initDataSource() throws SQLException {
        Connection conn = new DataSourceConfig.Builder(datasourceUrl, datasourceUsername, datasourcePassword).build().getConn();
        InputStream inputStream = CodeGenerator.class.getResourceAsStream("/sql/init.sql");
        ScriptRunner scriptRunner = new ScriptRunner(conn);
        scriptRunner.setAutoCommit(true);
        scriptRunner.runScript(new InputStreamReader(inputStream));
        conn.close();
    }

}
